﻿using System.Net.NetworkInformation;
using System.Text.RegularExpressions;

namespace DeviceAlarmService.SystemService
{
    public class ConnectionCheck
    {
        /// <summary>
        /// ip 检查
        /// </summary>
        /// <param name="strIP"></param>
        /// <returns></returns>
        public bool IsIpEffective(string ipAddress)
        {
            if (IsValidIpAddress(ipAddress))
            {
                //OperationLog($"IP地址：{ipAddress} 有效地址");
            }
            else
            {
                throw new($"IP地址：{ipAddress} 无效地址");
            }

            Ping pingSender = new Ping();
            try
            {
                PingReply reply = pingSender.Send(ipAddress);

                if (reply != null && reply.Status == IPStatus.Success)
                {
                    // OperationLog($"IP地址：{ipAddress} 连接可达");
                    return true;
                }
                else
                {
                    throw new($"IP地址：{ipAddress} 无法访问");
                }
            }
            catch (Exception ex)
            {
                throw new($"IP地址：（检测出现错误）{ex.Message}");
            }
        }

        private bool IsValidIpAddress(string ipAddress)
        {
            Regex rx = new Regex(@"\b((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))\b");
            if (rx.IsMatch(ipAddress) == false)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}
